package com.agileai.portal.controller.forum;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.forum.ForumSectionInfoTreeManage;
import com.agileai.portal.bizmoduler.forum.UserLevel8BBSUserInfoManage;
import com.agileai.portal.extend.forum.ForumPrivilegeHelper;
import com.agileai.util.DateUtil;

/**
 * generated by miscdp
 */
public class ForumPostHandler extends SimpleHandler{
	private static String HOTSPOT = "hotspot";
	private static String INTEGRALCHANGE = "INTEGRAL_CHANGE";
	private static String POSTINGS = "POSTINGS";
	private static String ORDINARYPOSTS = "ORDINARY_POSTS";
	private static String N = "N";
	private static String ERROR = "error";
	private static String HASREPORT = "HAS_REPORT";
	public ForumPostHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String responseText = " ";
		String resouce =  param.get("resouce");
		String maxCountValue = param.get("maxCount");
		int maxCount = Integer.parseInt(maxCountValue);
		JSONObject jsonObject = new JSONObject();
		ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
		List<DataRow> records = new ArrayList<DataRow>();
		if(HOTSPOT.equals(resouce) || HOTSPOT == resouce){
			records = forumSectionInfoTreeManage.findHotPostRecords(0,20);
		}else{
			records = forumSectionInfoTreeManage.findNewPostRecords();
		}
		try {
			int count = (maxCount > records.size()) ? records.size():maxCount;
			JSONArray jsonArray = new JSONArray();
			jsonObject.put("records", jsonArray);
			for (int i=0;i < count;i++){
				DataRow row = records.get(i);
				JSONObject tempJsonObject = new JSONObject();
				String fpmId = row.stringValue("FPM_ID");
				String fpmTitle = row.stringValue("FPM_TITLE");
				String fpmType = row.getString("FPM_TYPE");
				jsonArray.put(tempJsonObject);
				tempJsonObject.put("fpmId", fpmId);
				tempJsonObject.put("fpmTitle", fpmTitle);
				tempJsonObject.put("fpmType", fpmType);
			}
			String content = jsonObject.toString();
			responseText = content;
			
			this.setAttribute("content",jsonObject.toString());
		} catch (Exception e) {
			this.log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer mobileCreatePostForumInfo (DataParam param){
		String responseText = FAIL;
    	try {
        	String inputString = this.getInputString();
        	JSONObject jsonObject = new JSONObject(inputString);
        	String sectionCode = jsonObject.get("fciCode").toString();//板块编码
        	String fpmTitle = jsonObject.get("title").toString();//标题
        	String fpmExpression = jsonObject.get("fpmExpression").toString();//帖子类型
        	String fpmRewardPoints = jsonObject.get("points").toString();//分数
        	String fpmContent = jsonObject.get("fpmContent").toString();//内容
        	
        	ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
    		User user = (User)this.getUser();
    		String userCode = user.getUserCode();
    		ForumPrivilegeHelper forumPrivilegeHelper = new ForumPrivilegeHelper(user);
        	String fuLevel = forumPrivilegeHelper.getFuLevel();
    		String fuIntegral = forumPrivilegeHelper.getFuIntegral();
    		String fuLevelVal = forumSectionInfoTreeManage.getFuLevelValRecord(fuLevel);
    		String userId = forumSectionInfoTreeManage.getFuIdRecord(userCode);
    		String postScores = forumSectionInfoTreeManage.getPostScores(INTEGRALCHANGE,POSTINGS);
    		DataRow sectionInfoRow = forumSectionInfoTreeManage.getSectionInfo(sectionCode);
    		String sectionId = sectionInfoRow.getString("FCI_ID");
    		
        	int fuIntegralVal = 0;
    		if("".equals(fpmRewardPoints) || null == fpmRewardPoints){
    			fpmRewardPoints = "";
    			fuIntegralVal = Integer.valueOf(fuIntegral) + Integer.valueOf(fuLevelVal) * Integer.valueOf(postScores);
    		}else{
    			int fpmRewardPointsNum = Integer.valueOf(fpmRewardPoints);
    			fuIntegralVal = Integer.valueOf(fuIntegral) + Integer.valueOf(fuLevelVal) * Integer.valueOf(postScores)  - fpmRewardPointsNum;
    		}
        	
    		String fuIntegralStr = String.valueOf(fuIntegralVal);
    		UserLevel8BBSUserInfoManage userLevel8BBSUserInfoManage = this.lookupService(UserLevel8BBSUserInfoManage.class);
    		userLevel8BBSUserInfoManage.updateUserFuIntegral(userId,fuIntegralStr);
    		
        	DataParam dataParam = new DataParam();
    		dataParam.put("FPM_ID", KeyGenerator.instance().genKey());
    		dataParam.put("FCI_ID",sectionId);
    		dataParam.put("FPM_USERID",userId);
    		dataParam.put("FPM_EXPRESSION",fpmExpression);
    		dataParam.put("FPM_TITLE",fpmTitle);
    		dataParam.put("FPM_CONTENT",fpmContent);
    		dataParam.put("FPM_CREATE_TIME", new Date());
    		dataParam.put("FPM_CLICK_NUMBER", 0);
    		dataParam.put("FPM_REWARD_POINTS", fpmRewardPoints);
    		dataParam.put("FPM_IS_TOP", N);
    		dataParam.put("FPM_SECTION_TOP", N);
    		dataParam.put("FPM_TYPE", ORDINARYPOSTS);
    		forumSectionInfoTreeManage.createPostMessageRecord(dataParam);
        	responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer mobileCreateRepleceForumInfo(DataParam param){
		String responseText = FAIL;
		try {
        	String inputString = this.getInputString();
        	JSONObject jsonObject = new JSONObject(inputString);
        	String fpmId = param.getString("fpmId");
        	String replyFloor = jsonObject.get("replyFloor").toString();//回复楼数
        	String friContent = jsonObject.get("friContent").toString();
        	
        	User user = (User)this.getUser();
    		String userCode = user.getUserCode();
        	
        	ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
        	String fuId = forumSectionInfoTreeManage.getFuIdRecord(userCode);
        	
        	DataParam dataParam = new DataParam();
    		dataParam.put("FRI_ID", KeyGenerator.instance().genKey());
    		dataParam.put("FRI_CONTENT",friContent);
    		dataParam.put("FRI_USERID",fuId);
    		dataParam.put("FPM_ID",fpmId);
    		dataParam.put("FRI_REPORT_NUM",replyFloor);
    		dataParam.put("FRI_TIME", new Date());
    		
    		forumSectionInfoTreeManage.createRepliesInfoRecord(dataParam);
        	responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer mobileUpdatePostClickNumber(DataParam param) {
		String responseText = FAIL;
		try {
			String inputString = this.getInputString();
        	JSONObject jsonObject = new JSONObject(inputString);
        	String fpmId = jsonObject.get("fpmId").toString();
        	String fpmClickNumberStr = jsonObject.get("fpmClickNumber").toString();
			int fpmClickNumber = Integer.valueOf(fpmClickNumberStr);
			fpmClickNumber = fpmClickNumber + 1;
			ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
			forumSectionInfoTreeManage.updateFpmClickNumberRecord(fpmId, fpmClickNumber);
			responseText = SUCCESS;
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer mobileCreateForumFavorite(DataParam param) {
		String responseText = FAIL;
		try {
        	String fpmId = param.getString("fpmId");
        	User user = (User)this.getUser();
    		String userCode = user.getUserCode();
        	ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
        	String fuId = forumSectionInfoTreeManage.getFuIdRecord(userCode);
        	DataRow row = forumSectionInfoTreeManage.getForumPostMessageRecord(fpmId);
        	String fpmTitle = row.getString("FPM_TITLE");
        	int count = forumSectionInfoTreeManage.getForumFavoriteRecord(fpmId, fuId);
        	if(count == 0){
        		forumSectionInfoTreeManage.createForumFavoriteRecord(fpmId, fuId, fpmTitle);
        	}else{
        		forumSectionInfoTreeManage.delForumFavoriteRecord(fpmId, fuId);
        	}
        	responseText = SUCCESS;
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer mobilefindForumManageListInfos(DataParam param) {
		String responseText = FAIL;
		try {
        	User user = (User)this.getUser();
    		String userCode = user.getUserCode();
        	ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
        	String fuId = forumSectionInfoTreeManage.getFuIdRecord(userCode);
        	
        	List<DataRow> reportRecords = forumSectionInfoTreeManage.mobilefindForumReportListInfos(fuId);
        	JSONObject jsonObject1 = new JSONObject();
        	JSONArray jsonArray1 = new JSONArray();
        	int reportCount = 0;
        	if(reportRecords.size() !=0){
        		for(int i=0;i<reportRecords.size();i++){
            		DataRow row = reportRecords.get(i);
            		JSONObject jsonObject11 = new JSONObject();
            		String id= row.stringValue("FPM_ID");
        			reportCount = reportRecords.size();
        			jsonObject11.put("id",id );
            		jsonObject11.put("title", row.stringValue("FPM_TITLE"));
            		String time = row.stringValue("FRR_TIME");
            		if(!time.isEmpty()){
            			time = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, row.getTimestamp("FRR_TIME"));
            			jsonObject11.put("time", time);
            		}else{
            			continue;
            		}
            		jsonObject11.put("clickNum", row.stringValue("FPM_CLICK_NUMBER"));
            		jsonObject11.put("category", row.stringValue("FCI_NAME"));
            		String mobileContent = row.stringValue("FPM_CONTENT_MOBILE");
        			if(mobileContent == null || mobileContent.isEmpty()){
        				String pcContent =  row.stringValue("FPM_CONTENT");
        				pcContent = this.filterHtml(pcContent);
        				jsonObject11.put("content",pcContent);
        			}else{
        				jsonObject11.put("content",mobileContent);
        			}
            		String type = "";
    				if("ESSENCE_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "essence";
    				}else if("KEY_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "key";
    				}else if("ORDINARY_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "ordinary";
    				}else if("GARBAGE_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "garbage";
    				}
    				jsonObject11.put("count", row.stringValue("FRI_ID_COUNT"));
    				jsonObject11.put("type", type);
            		jsonArray1.put(jsonObject11);
            	}
        	}else{
        		JSONObject jsonObject11 = new JSONObject();
        		jsonObject11.put("reportTitle", ERROR);
        		jsonArray1.put(jsonObject11);
        	}
        	
        	List<DataRow> records = forumSectionInfoTreeManage.mobilefindForumGarbageListInfos(fuId);
        	int garbageCount = 0;
        	JSONArray jsonArray2 = new JSONArray();
        	if(records.size() != 0){
        		garbageCount = records.size();
        		for(int i=0;i<records.size();i++){
            		DataRow row = records.get(i);
            		JSONObject jsonObject21 = new JSONObject();
            		String id = row.stringValue("FPM_ID");
        			jsonObject21.put("id", id);
            		jsonObject21.put("title", row.stringValue("FPM_TITLE"));
            		String time = row.stringValue("FRR_TIME");
            		if(!time.isEmpty()){
            			time = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, row.getTimestamp("FRR_TIME"));
            			jsonObject21.put("time", time);
            		}else{
            			continue;
            		}
            		jsonObject21.put("clickNum", row.stringValue("FPM_CLICK_NUMBER"));
            		jsonObject21.put("category", row.stringValue("FCI_NAME"));
            		
            		String mobileContent = row.stringValue("FPM_CONTENT_MOBILE");
        			if(mobileContent == null || mobileContent.isEmpty()){
        				String pcContent =  row.stringValue("FPM_CONTENT");
        				pcContent = this.filterHtml(pcContent);
        				jsonObject21.put("content",pcContent);
        			}else{
        				jsonObject21.put("content",mobileContent);
        			}
        			
            		String type = "";
    				if("ESSENCE_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "essence";
    				}else if("KEY_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "key";
    				}else if("ORDINARY_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "ordinary";
    				}else if("GARBAGE_POSTS".equals(row.stringValue("FPM_TYPE"))){
    					type = "garbage";
    				}
    				jsonObject21.put("type", type);
    				jsonObject21.put("count", row.stringValue("FRI_ID_COUNT"));
            		jsonArray2.put(jsonObject21);
            	}
        	}else{
        		JSONObject jsonObject21 = new JSONObject();
        		jsonObject21.put("garbageTitle", ERROR);
        		jsonArray2.put(jsonObject21);
        	}
        	jsonObject1.put("reportCount", reportCount);
        	jsonObject1.put("report", jsonArray1);
        	jsonObject1.put("garbageCount", garbageCount);
        	jsonObject1.put("garbage", jsonArray2);
			responseText = jsonObject1.toString();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	 private String filterHtml(String str) {
    	String regxp = "<([^>]*)>";
		Pattern pattern = Pattern.compile(regxp);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}
	 
	 @PageAction
		public ViewRenderer mobileReportPost(DataParam param) {
			String responseText = FAIL;
			try {
				String inputString = this.getInputString();
	    		JSONObject jsonObject = new JSONObject(inputString);
	        	String fpmId = jsonObject.getString("fpmId");
	        	
				ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
				DataRow managePostInfoRow = forumSectionInfoTreeManage.getManagePostInfoRecord(fpmId);
				
				String fpmUserId = managePostInfoRow.getString("FPM_USERID");
				UserLevel8BBSUserInfoManage userLevel8BBSUserInfoManage = this.lookupService(UserLevel8BBSUserInfoManage.class);
				DataRow fuIndoRow = userLevel8BBSUserInfoManage.getFuInfoRecord(fpmUserId);
				String fuIntegral = fuIndoRow.getString("FU_INTEGRAL");
				String fuleve = fuIndoRow.getString("FU_LEVEL");
				
				DataRow codeListRow =  forumSectionInfoTreeManage.findCodeListRecord(fuleve);
				String weightStr = codeListRow.getString("CODE_NAME");
				
				int weight = Integer.valueOf(weightStr);
				int fractionInt = -3 ;
				int fuIntegralVal = Integer.valueOf(fuIntegral);
				fuIntegralVal = fuIntegralVal + fractionInt * weight;
				
				String fuIntegralStr = String.valueOf(fuIntegralVal);
				userLevel8BBSUserInfoManage.updateUserFuIntegral(fpmUserId,fuIntegralStr);
				forumSectionInfoTreeManage.updateFpmTypeRecord(fpmId,"GARBAGE_POSTS");
				forumSectionInfoTreeManage.updateFpmReport(fpmId,"HAS_CONFIRM_REPORT");
				
				
				List<DataRow> records = forumSectionInfoTreeManage.findforumRepliesInfoRecords(fpmId);
				
				for(int i=0;i<records.size();i++){
					DataRow row = records.get(i);
					String replyState = row.stringValue("FRI_STATE");
					if(HASREPORT.equals(replyState)){
						String friId = row.getString("FRI_ID");
						String friUserId = row.getString("FRI_USERID");
						
						DataRow replyUserInfoRow = userLevel8BBSUserInfoManage.getFuInfoRecord(friUserId);
						String replyUserIntegral = replyUserInfoRow.getString("FU_INTEGRAL");
						String replyUserleve = replyUserInfoRow.getString("FU_LEVEL");
						
						DataRow replyCodeListRow =  forumSectionInfoTreeManage.findCodeListRecord(replyUserleve);
						String replyWeightStr = replyCodeListRow.getString("CODE_NAME");
						
						int replyWeight = Integer.valueOf(replyWeightStr);
						int replyFractionInt = -3 ;
						int replyFuIntegralVal = Integer.valueOf(replyUserIntegral);
						replyFuIntegralVal = replyFuIntegralVal + replyFractionInt * replyWeight;
						
						String repluFuIntegralStr = String.valueOf(replyFuIntegralVal);
						userLevel8BBSUserInfoManage.updateUserFuIntegral(friUserId,repluFuIntegralStr);
						forumSectionInfoTreeManage.updateFriState(friId,"HAS_CONFIRM_REPORT");
					}else{
						continue;
					}
				}
				responseText = SUCCESS;
			} catch (Exception e) {
				log.error(e.getLocalizedMessage(), e);
			}
			return new AjaxRenderer(responseText);
		}
		
		@PageAction
		public ViewRenderer mobileCancelReportPost(DataParam param) {
			String responseText = FAIL;
			try {
				String inputString = this.getInputString();
	    		JSONObject jsonObject = new JSONObject(inputString);
	        	String fpmId = jsonObject.getString("fpmId");
	        	
				ForumSectionInfoTreeManage forumSectionInfoTreeManage = this.lookupService(ForumSectionInfoTreeManage.class);
				DataRow managePostInfoRow = forumSectionInfoTreeManage.getManagePostInfoRecord(fpmId);

				String fpmUserId = managePostInfoRow.getString("FPM_USERID");
				UserLevel8BBSUserInfoManage userLevel8BBSUserInfoManage = this.lookupService(UserLevel8BBSUserInfoManage.class);
				DataRow fuIndoRow = userLevel8BBSUserInfoManage.getFuInfoRecord(fpmUserId);
				String fuIntegral = fuIndoRow.getString("FU_INTEGRAL");
				String fuleve = fuIndoRow.getString("FU_LEVEL");
				
				DataRow codeListRow =  forumSectionInfoTreeManage.findCodeListRecord(fuleve);
				String weightStr = codeListRow.getString("CODE_NAME");
				
				int weight = Integer.valueOf(weightStr);
				int fractionInt = 3 ;
				int fuIntegralVal = Integer.valueOf(fuIntegral);
				fuIntegralVal = fuIntegralVal + fractionInt * weight;
				
				String fuIntegralStr = String.valueOf(fuIntegralVal);
				userLevel8BBSUserInfoManage.updateUserFuIntegral(fpmUserId,fuIntegralStr);
				forumSectionInfoTreeManage.updateFpmTypeRecord(fpmId,"ORDINARY_POSTS");
				forumSectionInfoTreeManage.updateFpmReport(fpmId,"NO_REPORT");
				List<DataRow> reportRecords = forumSectionInfoTreeManage.findforumReplrtRecords(fpmId);
				String frrIds ="";
				for(int i=0;i<reportRecords.size();i++){
					DataRow row = reportRecords.get(i);
					String frrId = row.getString("FRR_ID");
					frrIds = frrId+","+frrIds;
				}
				forumSectionInfoTreeManage.deleForumReplrtRecords(frrIds);
				
				
				
				List<DataRow> records = forumSectionInfoTreeManage.findforumRepliesInfoRecords(fpmId);
				
				for(int i=0;i<records.size();i++){
					DataRow row = records.get(i);
					String replyState = row.stringValue("FRI_STATE");
					if(HASREPORT.equals(replyState)){
						String friId = row.getString("FRI_ID");
						String friUserId = row.getString("FRI_USERID");
						
						DataRow replyUserInfoRow = userLevel8BBSUserInfoManage.getFuInfoRecord(friUserId);
						String replyUserIntegral = replyUserInfoRow.getString("FU_INTEGRAL");
						String replyUserleve = replyUserInfoRow.getString("FU_LEVEL");
						
						DataRow replyCodeListRow =  forumSectionInfoTreeManage.findCodeListRecord(replyUserleve);
						String replyWeightStr = replyCodeListRow.getString("CODE_NAME");
						
						int replyWeight = Integer.valueOf(replyWeightStr);
						int replyFractionInt = 3 ;
						int replyFuIntegralVal = Integer.valueOf(replyUserIntegral);
						replyFuIntegralVal = replyFuIntegralVal + replyFractionInt * replyWeight;
						
						String repluFuIntegralStr = String.valueOf(replyFuIntegralVal);
						userLevel8BBSUserInfoManage.updateUserFuIntegral(friUserId,repluFuIntegralStr);
						forumSectionInfoTreeManage.updateFriState(friId,"NO_REPORT");
						
						List<DataRow> replyReportRecords = forumSectionInfoTreeManage.findforumReplrtRecords(friId);
						String reportIds ="";
						for(int j=0;j<replyReportRecords.size();j++){
							DataRow idRow = replyReportRecords.get(j);
							String reoirtId = idRow.getString("FRR_ID");
							reportIds = reoirtId+","+reportIds;
						}
						forumSectionInfoTreeManage.deleForumReplrtRecords(reportIds);
					}else{
						continue;
					}
				}
				
				
				responseText = SUCCESS;
			} catch (Exception e) {
				log.error(e.getLocalizedMessage(), e);
			}
			return new AjaxRenderer(responseText);
		}
}